﻿using ClothingShopping.Core.Configuration;
using ClothingShopping.Data;
using ClothingShopping.Dto;
using ClothingShopping.Dto.AccountDto;
using ClothingShopping.Dto.Enums;
using ClothingShopping.IRepository;
using ClothingShopping.IService;
using ClothingShopping.Util.SecurityHelper;
using Microsoft.IdentityModel.Tokens;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Text;

namespace ClothingShopping.Service
{
    public class UserService:IUserService
    {
        #region Fields
        private readonly IUserRepository _userRepository;
        #endregion

        #region Ctors
        public UserService(IUserRepository userRepository)
        {
            _userRepository = userRepository;
        }
        #endregion

        #region Methods
        /// <summary>
        /// 注册用户
        /// </summary>
        /// <param name="user"></param>
        /// <returns></returns>
        /// <exception cref="Exception"></exception>
        public async Task<IResultOutput> AddUserAsync(User user)
        {
            try
            {
                user.md5_password = EncryptionProcessing.GetPwdMd5(user.md5_password);
                var result = await _userRepository.InsertAsync(user);
                if(result == null)
                    throw new Exception("注册用户失败");//抛出错误，回滚事务
                
                return ResultOutput.Ok("注册用户成功");
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
        }

        public async Task<IResultOutput> DeleteUserAsync(int id)
        {
            try
            {
                int result;
                result = await _userRepository.DeleteAsync(id);
                if (result < 1)
                    throw new Exception("删除失败");
                return ResultOutput.Ok("删除成功");
            }
            catch (Exception ex)
            {
                return ResultOutput.Error(ex.Message);
            }
        }

        public async Task<User> GetUserByIdAsync(int id = 0, string? userName = null)
        {
            User result=null;
            if (userName != null)
                result = await _userRepository.Orm.Select<User>()
                                   .Where(user => user.user_name == userName).ToOneAsync();
            
            if (id > 0)
                result = await _userRepository.FindAsync(id);
            return result;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="user"></param>
        /// <returns></returns> 
        /// <exception cref="Exception"></exception>
        public async Task<IResultOutput> UpdateUserAsync(UserDto userDto)
        {
            try
            {
                int result;
                result = await _userRepository.Orm.Update<User>(1)
                    .Set(it => new User()
                    {
                        user_name = userDto.user_name,
                        SEX = userDto.SEX,
                        email = userDto.email,
                        phone = userDto.phone,
                        modifier = userDto.modifier,
                        mTime = DateTime.Now,
                        state = userDto.state
                    })
                    .Where(it => it.user_id == userDto.user_id).ExecuteAffrowsAsync();
                if (result <1) 
                    throw new Exception("找不到用户");
                return ResultOutput.Ok("修改成功！");
                
            }
            catch (Exception ex)
            {
                return ResultOutput.Error(ex.Message);
            }
        }

        public async Task<IResultOutput> LoginAsync(string login_name,string pwd)
        {
            //if (loginInputDto.loginType == LoginType.账号登录)
            //{
                login_name = login_name.Trim();
                var user = _userRepository.Orm.Select<User>()
                    .Where(it => it.login_name == login_name)
                    .ToOne();
                
                 if (user == null)
                {
                    return ResultOutput.Error("用户不存在");
                }
                else if (user.md5_password != EncryptionProcessing.GetPwdMd5(pwd))
                {
                    return ResultOutput.Error("密码错误");
                }else
                {
                    //登录成功
                    var claims = new Claim[]
                    {
                        new Claim(ClaimTypes.Name, user.user_name),
                        new Claim(type:"Id",user.user_id.ToString()),
                        new Claim(type:"LoginName",user.login_name)
                    };
                    var key=new SymmetricSecurityKey(Encoding.UTF8.GetBytes("我是密钥我是密钥我是密钥"));
                var signingCredentials = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);

                //issuer为应用程序的地址，audience是Token的受理者
                var token = new JwtSecurityToken(
                        issuer: "http://localhost:44362",
                        audience: "http://localhost:7214",
                        claims:claims,
                        notBefore:DateTime.Now,
                        expires: DateTime.Now.AddMinutes(120),
                        signingCredentials: signingCredentials
                        );
                    var jwtToken= new JwtSecurityTokenHandler().WriteToken(token);
                return ResultOutput.Ok(jwtToken);

                }
            //}
            //else
            //{//短信登录

            //}
        }

        public Task<IResultOutput> ChangePassword(ChangePwdInputDto changePwdInputDto)
        {
            throw new NotImplementedException();
        }

        #endregion
    }
}
